package net.e_agri.json;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import net.arnx.jsonic.JSON;
import net.e_agri.wap.section.Sectionalizer;

import java.util.logging.Logger;

public class JSonConverter {

	private static final Logger log = Logger.getLogger(JSonConverter.class.getName());
	
	public static String convertMatcher(Matcher mat, List<String> fields, Sectionalizer section){

		StringBuffer buf = new StringBuffer();
		StringBuffer logBuf = new StringBuffer();
		buf.append("{\"fields\":")
			.append(JSON.encode(fields));

		String sec = "";
		String val = "";
		Map<String,List<List<String>>> sectionMap = new LinkedHashMap<String,List<List<String>>>();
		List<List<String>> sectData = null;
		List<String> sectRec = null;
		int cnt = 0;

		while(mat.find()){
			sec = section.getSection(mat);
			if(!sectionMap.containsKey(sec))
				sectionMap.put(sec, new ArrayList<List<String>>());

			sectRec = new ArrayList<String>();
			for(int j=1; j<=mat.groupCount(); j++){
				val = mat.group(j);
			
				if(val.indexOf("&amp;")!=-1)
					val = val.substring(val.indexOf("&amp;")+5);

				sectRec.add(val.replace("\n","").replace("\r","").replace("&amp;", "&"));
			}
			
			cnt++;
			logBuf.append("\n\t").append(sectRec.toString());

			sectData = sectionMap.get(sec);
			sectData.add(sectRec);
			sectionMap.put(sec, sectData);
		}
		log.info(logBuf.toString());
		log.info("convertMatcher count:" + cnt);

		buf.append(",\"data\":")
			.append(JSON.encode(sectionMap))
		.append("}");
 
		return buf.toString();
	}
	
	public static String matcherToString(Matcher mat){

		int matCount = 0;
		StringBuffer buf = new StringBuffer();

        while(mat.find()){
        	matCount++;
        	buf.append("\t[").append(matCount).append("]");

        	for(int i=1; i<=mat.groupCount(); i++)
            	 buf.append("\t").append(mat.group(i));

        	buf.append("\n");
        }

		return buf.toString();
	}
}
